/*
 * ﻿Copyright (C) 2009-2013 NewMain Softech
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package com.newmainsoftech.gwetons.client;

import java.util.LinkedHashMap;

import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.Window;
import com.newmainsoftech.gwetons.client.timer.TimeredCracker;
import com.newmainsoftech.gwetons.client.timer.TimeredCracker.TimerSingletonControllerAttacher;
import com.newmainsoftech.gwetons.shared.timer.TimerEventListener;

public class TimerSingletonController {
	private static TimerSingletonController _instance = new TimerSingletonController();
	private TimerSingletonController() {
	}
	
	private static native int createInterval( TimeredCracker timeredCracker, int period) /*-{
		return $wnd.setInterval(
			function() { timeredCracker.@com.newmainsoftech.gwetons.client.timer.TimeredCracker::fire()(); },
			period
			);
	}-*/;
	
	private static native int createTimeout( TimeredCracker timeredCracker, int delay) /*-{
		return $wnd.setTimeout(
			function() { timeredCracker.@com.newmainsoftech.gwetons.client.timer.TimeredCracker::fire()(); },
			delay
			);
	}-*/;

	private static native void clearInterval( int id) /*-{
		$wnd.clearInterval( id);
	}-*/;
	
	private static native void clearTimeout( int id) /*-{
		$wnd.clearTimeout( id);
	}-*/;
	
	protected class TimerUnitModel {
		protected final int id;
		public int getId() {
			return id;
		}
		protected final TimeredCracker timeredCracker;
		public TimeredCracker getTimeredCracker() {
			return timeredCracker;
		}

		public TimerUnitModel( int id, TimeredCracker timeredCracker) {
			this.id = id;
			this.timeredCracker= timeredCracker;
		}		
	}
	protected TimerUnitModel createTimerUnitModelObject( int id, TimeredCracker timeredCracker) {
		return new TimerUnitModel( id, timeredCracker);
	}
	
	protected static LinkedHashMap<TimerEventListener, TimerUnitModel> timerEventListenerLinkedHashMap = 
		new LinkedHashMap<TimerEventListener, TimerUnitModel>();
	
	/**
	 * Cancels timer.
	 */
	public static void cancel( TimerEventListener timerEventListener) {
		if ( timerEventListener == null) return;
		TimerUnitModel timerUnitModel = timerEventListenerLinkedHashMap.get( timerEventListener);
		if ( timerUnitModel == null) return;
		if ( timerUnitModel.getTimeredCracker().isForRepeat()) clearInterval( timerUnitModel.id);
		else clearTimeout( timerUnitModel.id);
		timerEventListenerLinkedHashMap.remove( timerEventListener);
	}

	public static void cancelAll() {
		if ( timerEventListenerLinkedHashMap.isEmpty()) return;

		TimerEventListener[] timerEventListenerArray = 
			timerEventListenerLinkedHashMap.keySet().toArray( new TimerEventListener[ 0]);
		for( 
				int timerEventListenerIndex = timerEventListenerLinkedHashMap.size() - 1;
				timerEventListenerIndex > -1;
				timerEventListenerIndex--
				) 
		{
			TimerEventListener timerEventListener = timerEventListenerArray[ timerEventListenerIndex];
			cancel( timerEventListener);
		} // for
	}
	
	private static void hookWindowClosing() {
		// Catch the window closing event.
		Window.addCloseHandler(
			new CloseHandler<Window>() {
				public void onClose( CloseEvent<Window> event) {
					cancelAll();
				}
		});
	}
	static {
		hookWindowClosing();
	}

	protected class TimerEventHandOver implements TimerSingletonControllerAttacher {
		private final TimerEventListener timerEventListener;
		private final boolean forRepeat;
		public TimerEventHandOver( TimerEventListener timerEventListener, boolean forRepeat) {
			this.timerEventListener = timerEventListener;
			this.forRepeat = forRepeat;
		}
		
		public void fire() {
			if ( timerEventListener != null) timerEventListener.fire();
		}
		public void remove() {
			if ( timerEventListener == null) return;
			if ( forRepeat) return;
			timerEventListenerLinkedHashMap.remove( timerEventListener);			
		}
	} // protected class TimerEventHandOver implements TimerSingletonControllerAttacher
	protected TimerEventHandOver createTimerEventHandOverObject( 
			TimerEventListener timerEventListener, boolean forRepeat) 
	{
		return new TimerEventHandOver( timerEventListener, forRepeat);
	}
	
	public static void schedule( TimerEventListener timerEventListener, int delayMillis) {
		if ( timerEventListener == null) {
			throw new IllegalArgumentException( "timeredMethodHandler argument cannot be null.");
		}
		if (delayMillis <= 0) {
			throw new IllegalArgumentException( "delayMillis argument must be bigger than 0");
		}
		
		if ( !timerEventListenerLinkedHashMap.isEmpty()) {
			cancel( timerEventListener);
		}
		
		TimeredCracker timeredCracker = 
			new TimeredCracker( 
					false, 
					_instance.createTimerEventHandOverObject( timerEventListener, false)
					);
		int timerId = createTimeout( timeredCracker, delayMillis);
		timerEventListenerLinkedHashMap.put( 
				timerEventListener, 
				_instance.createTimerUnitModelObject( timerId, timeredCracker)
				);
	} // public static void schedule( TimeredMethodHandler timeredMethodHandler, int delayMillis)
	
	
	public static void scheduleRepeating( TimerEventListener timerEventListener, int periodMillis) {
		if ( timerEventListener == null) {
			throw new IllegalArgumentException( "timeredMethodHandler argument cannot be null.");
		}
		if (periodMillis <= 0) {
			throw new IllegalArgumentException( "periodMillis argument must be bigger than 0");
		}
		
		if ( !timerEventListenerLinkedHashMap.isEmpty()) {
			cancel( timerEventListener);
		}
		
		TimeredCracker timeredCracker = 
			new TimeredCracker( 
					true, 
					_instance.createTimerEventHandOverObject( timerEventListener, true)
					);
		int timerId = createInterval( timeredCracker, periodMillis);
		timerEventListenerLinkedHashMap.put( 
				timerEventListener, 
				_instance.createTimerUnitModelObject( timerId, timeredCracker)
				);
	} // public static void scheduleRepeating( TimerEventListenerIntf timerEventListener, int periodMillis)
}
